package com.bootdo.clouddo.core.security;

import com.bootdo.clouddo.domain.user.QaUsers;
import com.bootdo.clouddo.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import javax.servlet.http.HttpServletRequest;

public class OpenSDKAccessTokenUtil {

	/**
	 * 通过AccessToken获取已经登陆的用户/机构的实体
	 * @param accessToken
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T>T getSecureObjectFromToken(RedisAccessTokenStore tokenStore, String accessToken){
		Authentication authen = tokenStore.readAuthentication(accessToken);
		T loginedUser =  (T) authen.getPrincipal();

		return loginedUser;
	}

	public static <T>T refreshTokenUser(RedisAccessTokenStore tokenStore, String accessToken, QaUsers user){
		OAuth2Authentication authen = tokenStore.readAuthentication(accessToken);
		if(authen.getPrincipal() == null)
			return null;
		T loginedUser =  (T)  authen.getPrincipal();
		if(!(loginedUser instanceof QaUsers))
			return null;
		QaUsers lu = (QaUsers)loginedUser;
		// 更新当前用户
		BeanUtils.copyProperties(user, lu);
		// 更新缓存中用户信息
		tokenStore.storeAccessToken(tokenStore.readAccessToken(accessToken), authen);
		return loginedUser;
	}

	public static String getAccessToken(HttpServletRequest request){
		String accessToken = request.getHeader("Authorization");
		if(StringUtils.isNotEmpty(accessToken) && accessToken.contains(" "))
			accessToken = accessToken.split(" ")[1];
		else
			accessToken = request.getParameter("access_token");
		if(StringUtils.isEmpty(accessToken))
			return null;
		return accessToken;
	}


}
